package racegame.schedulerTasks;

import java.util.ArrayList;

import com.smartfoxserver.v2.entities.User;

import racegame.extensions.RaceGameZoneExtension;
import racegame.utils.WaitingList;

public class AutoCreateGamesTask implements Runnable {

	private RaceGameZoneExtension zoneExtension;
	
	public AutoCreateGamesTask(RaceGameZoneExtension extension) {
		
		this.zoneExtension = extension;
		
	}
	
	@Override
	public void run() {
		
		try {
    		WaitingList waitingPlayers = new WaitingList(zoneExtension.getWaitingList().getUsers());
    		zoneExtension.trace("WAITING USERS: " + waitingPlayers.getNumberWaiting());

    		if ( waitingPlayers.getUsers().size() >= 2 ) {
    			//start making game
    			zoneExtension.trace("Should start game");
        		
    			//We need even count of users to make games so we eliminate the odd one
        		if ( (waitingPlayers.getNumberWaiting() % 2) != 0 ) {
        			waitingPlayers.remove(waitingPlayers.getUsers().get(waitingPlayers.getNumberWaiting() - 1).getId());
	    		}
        		zoneExtension.trace("Should create " + waitingPlayers.getNumberWaiting() / 2 + " rooms");
        		for (int i = 0; i < waitingPlayers.getNumberWaiting(); i += 2) {
	    			ArrayList<Integer> players = new ArrayList<Integer>();
	    			players.add(waitingPlayers.getUsers().get(i).getId());
	    			players.add(waitingPlayers.getUsers().get(i+1).getId());
	    			zoneExtension.startGame(players);
	    		}
    			
    		} else {
    			zoneExtension.trace("Not Enough Players To Start Game");
    		}
    		
    	} catch (Exception e) {
    		e.printStackTrace();
		}

	}

}
